<?php

/**
 * ECSHOP 限时抢购函数库
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: iron $
 * $Id: lib_flashsale.php 17217 2017-02-27 23:44:08Z iron $
*/
date_default_timezone_set('Asia/Shanghai');
$GLOBALS['_CFG']['timezone'] = 0;
if (!defined('IN_ECS'))
{
    die('Hacking attempt');
}

/*

 * 取得优惠活动列表

 * @return   array

 */

function flashsale_list()

{

    $result = get_filter();

    if ($result === false)

    {

        /* 过滤条件 */

        $filter['keyword']    = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);

        if (isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax'] == 1)

        {

            $filter['keyword'] = json_str_iconv($filter['keyword']);

        }

        $filter['is_going']   = empty($_REQUEST['is_going']) ? 0 : 1;

        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'act_id' : trim($_REQUEST['sort_by']);

        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

        $where = "";

        if (!empty($filter['keyword']))

        {

            $where .= " AND act_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%'";

        }

        if ($filter['is_going'])

        {

            $now = gmtime();

            $where .= " AND start_time <= '$now' AND end_time >= '$now' ";

        }

        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('flashsale') .

                " WHERE 1 $where";

        $filter['record_count'] = $GLOBALS['db']->getOne($sql);

        /* 分页大小 */

        $filter = page_and_size($filter);

        /* 查询 */

        $sql = "SELECT * ".

                "FROM " . $GLOBALS['ecs']->table('flashsale') .

                " WHERE 1 $where ".

                " ORDER BY $filter[sort_by] $filter[sort_order] ".

                " LIMIT ". $filter['start'] .", $filter[page_size]";

        $filter['keyword'] = stripslashes($filter['keyword']);

        set_filter($filter, $sql);

    }

    else

    {

        $sql    = $result['sql'];

        $filter = $result['filter'];

    }

    $res = $GLOBALS['db']->query($sql);

    $list = array();

    while ($row = $GLOBALS['db']->fetchRow($res))

    {

        $row['start_date']  = local_date('Y-m-d', $row['start_date']);

        $row['end_date']  = local_date('Y-m-d', $row['end_date']);

        $row['start_time']  = secondtostr($row['start_time']);

        $row['end_time']    = secondtostr($row['end_time']);

        $list[] = $row;

    }

    return array('item' => $list, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);

}

// 获取当前日期当前时间正在运行的活动
function __ongoing_flashsale()
{
    $date_time_stamp = local_gettime();
    $time_stamp = strtosecond(local_date('H:i'));
    // $sql = "select * from flashsale where {$date_time_stamp} between start_date and end_date";
    // $flashsale = $GLOBALS['db']->getAll($sql);
    $sql = "select * from flashsale where {$date_time_stamp} between start_date and end_date and {$time_stamp} BETWEEN start_time and end_time";
    $flashsale = $GLOBALS['db']->getAll($sql);
    if ($flashsale)
    {
        foreach ($flashsale as $k => $row)
        {
            $flashsale[$k]['is_running'] = $time_stamp >= $row['start_time'] && $time_stamp <= $row['end_time'] ? 1 : 0;
            $flashsale[$k]['end'] = local_strtotime(local_date('Y-m-d ').secondtostr($row['end_time']));
        }
    }
    return $flashsale;
}

// 获取当前日期当前时间正在运行的活动
function ongoing_flashsale()
{
    $date_time_stamp = local_gettime();
    $time_stamp = strtosecond(local_date('H:i'));
    $sql = "select * from flashsale where {$date_time_stamp} between start_date and end_date and {$time_stamp} BETWEEN start_time and end_time";
    $flashsale = $GLOBALS['db']->getRow($sql);
    if ($flashsale)
    {
        $flashsale['is_running'] = $time_stamp >= $flashsale['start_time'] && $time_stamp <= $flashsale['end_time'] ? 1 : 0;
        $flashsale['end'] = local_strtotime(local_date('Y-m-d ').secondtostr($flashsale['end_time']));
    }
    return $flashsale;
}


function flashsale_details($data)
{
  if (!$data)
  {
      return [];
  }
  $time_now = local_strtotime(date('H:i:s'));
  $data['status'] = get_flashsale_status($data['start_time'], $data['end_time']);
  $goods_ids = function($ids)
  {
      foreach (explode(',', $ids) as $id)
      {
          yield $id;
      }
  };
  foreach ($goods_ids($data['act_range_ext']) as $id)
  {
      if (!$id)
      {
          return [];
      }
      $goods_info = get_simple_goods_info($id);
      $goods_info['goods_thumb'] = API_DATA('PHOTO', $goods_info['goods_thumb']);
      $data['goods'][] = $goods_info;
  }

  return $data;
}

function get_flashsale_status($start_time, $end_time)
{
    $time_now = strtosecond(local_date('H:i'));
    if ($time_now > $start_time && $time_now < $end_time)
    {
        return 1;
    }
    if ($time_now < $start_time)
    {
        return -1;
    }
    return 0;
}

function strtosecond($time)
{
    list($hour, $minute) = explode(':', $time);
    return $hour*3600+$minute*60;
}

function secondtostr($time)
{
    $minute_s = $time%3600;
    $hour_s = $time-$minute_s;
    return sprintf('%02d', $hour_s/3600).':'.sprintf('%02d', $minute_s/60);
}
